#define _CRT_SECURE_NO_WARNINGS 1
#include"List.h"
ListNode* BuyListNode(LTDataType x)
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	if (node == NULL)
	{
		perror("BuyListNode::malloc");
	}
	node->prev = NULL;
	node->next = NULL;
	node->data = x;
	return node;
}
ListNode* ListCreate()
{
	ListNode* pHead = BuyListNode(-1);
	pHead->next = pHead;
	pHead->prev = pHead;
	return pHead;
}
void ListPrint(ListNode* pHead)
{
	assert(pHead);
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		printf("<=%d=>", cur->data);
		cur = cur->next;
	}
	printf("Head\n");
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* tail = pHead->prev;
	ListNode* newnode = BuyListNode(x);
	tail->next = newnode;
	newnode->next = pHead;
	newnode->prev = tail;
	pHead->prev = newnode;
}
bool ListEmpty(ListNode* pHead)
{
	assert(pHead);
	/*if (pHead->next == pHead)
		return true;
	else
		return false;*/
	return pHead->next == pHead;
}
void ListPopBack(ListNode* pHead)
{
	assert(pHead);
	assert(!ListEmpty(pHead));
	ListNode* tail = pHead->prev;
	ListNode* tailPrev = tail->prev;
	tailPrev->next = pHead;
	pHead->prev = tailPrev;
	free(tail);
	tail = NULL;
}
void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* newnode = BuyListNode(x);
	newnode->prev = pHead;
	newnode->next = pHead->next;
	pHead->next->prev = newnode;
	pHead->next = newnode;
}

void ListPopFront(ListNode* pHead)
{
	assert(pHead);
	assert(!ListEmpty(pHead));
	ListNode* del = pHead->next;
	pHead->next = del->next;
	del->next->prev = pHead;
	free(del);
	del = NULL;
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	assert(!ListEmpty(pHead));
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}
void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = BuyListNode(x);
	ListNode* pos_prev = pos->prev;
	pos_prev->next = newnode;
	newnode->prev = pos_prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* pos_prev = pos->prev;
	pos_prev->next = pos->next;
	pos->next->prev = pos_prev;
	free(pos);
	pos = NULL;
}
void ListDestory(ListNode* pHead)
{
	assert(pHead);
	ListNode*cur=pHead->next;
	while (cur != pHead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(pHead);
}